package com.yhn.shortlink.project.service.imp;

import com.yhn.shortlink.project.service.UrlTitleService;
import lombok.SneakyThrows;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author yhn
 * @version 1.0
 * @description
 * @date 2024/8/6 19:27
 */
@Service
public class UrlTitleServiceImpl implements UrlTitleService {
    /**
     * 根据url获取原始网站的标题
     * @param url url
     * @return 网站标题
     */
    @SneakyThrows
    @Override
    public String getTitleByUrl(String url) {
        URL targetUrl = new URL(url);
        HttpURLConnection urlConnection = (HttpURLConnection)targetUrl.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();
        int responseCode = urlConnection.getResponseCode();
        if(responseCode == HttpURLConnection.HTTP_OK){
            Document document = Jsoup.connect(url).get();
            return  document.title();
        }
        return "error";
    }
}
